﻿(function($) {
    $.fn.ZWEditor = function(option) {
        window.ZW = new zw_editor(this, option);
    }

    var zw_editor = function(textbox, option) {
        this.textbox = textbox;
        this.setting = {
            width: 480,
            height: 80,
            maxWord: 140,
            topicNotify: '请在这里输入自定义话题',
            wordNotify: '您还可以输入*个字符',
            btnOKText: '广播',
            btnOK: false
        };
        $.extend(this.setting, option);
        this.scriptPath = '';
        this.cursorPosi = {
            start: 0,
            end: 0
        }
        this.faceDesc = ['飞机', '给力', '神马', '浮云', '奥特曼', '免子', '熊猫', '呵呵', '嘻嘻', '哈哈', '爱你', '风扇',
            '晕', '泪', '馋', '抓狂', '哼', '抱抱', '可爱', '怒', '汗', '困', '冰棍', '害羞', '睡', '钱', '偷笑', '酷', '衰', '吃惊', '闭嘴',
            '鄙视', '抠鼻', '西瓜', '花心', '鼓掌', '失望', '思考', '生病', '亲亲', '怒骂', '太开心', '懒得理你', '右哼哼', '照相机',
            '左哼哼', '嘘', '委屈', '吐', '可怜', '打哈气', '顶', '疑问', '做鬼脸', '合作', '自行车', '耶', 'good', '弱', '不要', 'ok',
            '赞', '来', '蛋糕', '伤心', '钟', '织', '猪头', '话筒', '月亮', '太阳', '下雨', '围观', '威武'];
        this.checkSetting();
        this.init();
        this.initLayer();
    }
    zw_editor.prototype = {
        checkSetting: function() {
            this.setting.topicNotify = '#' + this.setting.topicNotify + '#';

            if (this.setting.width < 480) {
                this.setting.width = 480;
            }

            if (this.setting.height < 80) {
                this.setting.height = 80;
            }
        },
        init: function() {
            var _this = this;
            this.textbox.css({ width: this.setting.width, height: this.setting.height });
            this.textbox.wrap('<div id="ebox" class="ebox" style="min-height:' + (this.setting.height) + 'px;min-width:' + this.setting.width + 'px;"></div>').show();
            $('#ebox').wrap('<div id="zw-editor" class="zw-editor" style="width:' + (this.setting.width + 10) + 'px"></div>');
            $('#zw-editor').append('<div class="btnbar"><a class="face" href="javascript:;">表情</a>' +
                '<a class="img" href="javascript:;">图片</a><a class="topic" href="javascript:;">话题</a>' +
                '<span class="btnok"><input id="btn_publish_blog" type="button" value="' + this.setting.btnOKText + '" /></span>' +
                '<span id="wordtracer" class="wordtracer">' + this.getWordNotify() + '</span>' +
                '<div class="clr"></div></div>');
            this.textbox.keyup(function(event) { _this.traceCursorPosi(this, event); _this.wordTrace() });
            this.textbox.focus(function(event) { _this.traceCursorPosi(this, event) });
            this.textbox.select(function(event) { _this.traceCursorPosi(this, event) });
            this.textbox.mousemove(function(event) { _this.traceCursorPosi(this, event) });
            this.textbox.blur(function(event) { _this.wordTrace() });
            this.wordTrace();

            $('a.face').click(function(event) { _this.btnFaceClick(this, event); event.stopPropagation(); event.preventDefault(); });
            $('a.img').click(function(event) { _this.btnImgClick(this, event); event.stopPropagation(); event.preventDefault(); });
            $('a.topic').click(function(event) { _this.btnTopicClick(); });
            $('body').click(function() { $('#zw_layer').hide() });
            $('#btn_publish_blog').click(function(event) { _this.btnOKClick(this, event); });

            var temp = $(document).find('script[src*="zw-editor"]');
            if (temp && temp.length > 0) {
                temp = temp.length == 1 ? temp : temp[0];
                var fullPath = temp.attr('src');
                var temp = fullPath.split('/');
                temp.pop()
                this.scriptPath = temp.join('/');
            }
        },
        initLayer: function() {
            $.get(this.scriptPath + '/layer.htm', function(html) {
                $('body').append(html);
            });
        },
        hasTopicSetted: function() {
            var regex = new RegExp(this.setting.topicNotify);
            if (regex.test(this.textbox.val())) {
                this.selectTopicNotify();
                return false;
            }
            return true;
        },
        btnTopicClick: function() {
            if (!this.hasTopicSetted()) {
                return;
            }
            this.insertContent(this.setting.topicNotify);
            this.selectTopicNotify();
        },
        btnFaceClick: function(el, event) {
            if ($('#content_container img[mark="zwface"]').length > 0 && $('#zw_layer').is(':visible')) {
                return;
            }

            var posi = $(el).offset();
            var faceHtml = '<ul class="faces">';

            for (var i = 1; i < 75; i++) {
                faceHtml += '<li><a title="' + this.faceDesc[i - 1] + '" href="javascript:;">' +
            '<img mark="zwface" alt="' + this.faceDesc[i - 1] + '" src="' + this.scriptPath + '/face/' + i + '.gif" /></a></li>';
            }

            faceHtml += '</ul><div class="clr"></div>';
            this.showLayer(posi, faceHtml);

            var _this = this;
            $('ul.faces a').click(function(event) {
                _this.insertContent('[' + $(this).attr('title') + ']');
                $('#zw_layer').hide();
                event.stopPropagation();
                event.preventDefault();
            });
        },
        btnImgClick: function(el, event) {
            var posi = $(el).offset();
            this.showLayer(posi, 'upload image from here');
        },
        btnOKClick: function(el, event) {
            var val = $.trim(this.textbox.val());
            if (val == '') {
                this.textbox.focus();
            }
            else if (this.setting.btnOK && $.isFunction(this.setting.btnOK)) {
                if (this.hasTopicSetted()) {
                    this.setting.btnOK.call(null, val);
                }
            }
        },
        insertContent: function(content) {
            var start = 0, end = 0;

            if ($.browser.msie) {
                start = this.cursorPosi.start;
                end = this.cursorPosi.end;
            }
            else {
                var tbox = document.getElementById(this.textbox.attr('id'));
                start = tbox.selectionStart;
                end = tbox.selectionEnd;
            }

            var val = this.textbox.val();
            var leftStr = val.substr(0, start);
            var rightStr = val.substr(end);
            this.textbox.val(leftStr + content + rightStr);
            this.wordTrace();
        },
        showLayer: function(posi, html) {
            $('#content_container').html(html ? html : '(none information to see)');
            $('#zw_layer').show().offset({ left: posi.left, top: posi.top + 25 });
        },
        getTopicNotifyPosi: function() {
            var val = this.textbox.val();
            var str = this.setting.topicNotify.replace(/#/g, '');
            var arry1 = val.split('#' + str);
            var arry2 = val.split(str + '#');
            var start = arry1[0].length + 1;
            var end = arry2[0].length + str.length;
            return { start: start, end: end };
        },
        selectTopicNotify: function() {
            var tbox = document.getElementById(this.textbox.attr('id'));
            var posi = this.getTopicNotifyPosi();
            //is ie
            if ($.browser.msie) {
                var range = tbox.createTextRange();
                range.collapse();
                range.moveEnd('character', posi.end);
                range.moveStart('character', posi.start);
                range.select();
                return;
            }
            //not ie
            tbox.focus();
            tbox.setSelectionRange(posi.start, posi.end);
        },
        traceCursorPosi: function(el, event) {
            var start = 0, end = 0;
            var textBox = el;
            //is ie
            if ($.browser.msie) {
                var range = document.selection.createRange();
                if (range.parentElement().id == textBox.id) {

                    var range_all = document.body.createTextRange();
                    range_all.moveToElementText(textBox);

                    for (start = 0; range_all.compareEndPoints('StartToStart', range) < 0; start++) {
                        range_all.moveStart('character', 1);
                    }

                    for (var i = 0; i <= start; i++) {
                        if (textBox.value.charAt(i) == 'n') {
                            start++;
                        }
                    }

                    range_all = document.body.createTextRange();
                    range_all.moveToElementText(textBox);

                    for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end++) {
                        range_all.moveStart('character', 1);
                    }

                    for (var i = 0; i <= end; i++) {
                        if (textBox.value.charAt(i) == 'n')
                            end++;
                    }
                }
            }
            //not ie
            else {
                start = textBox.selectionStart;
                end = textBox.selectionEnd;
            }
            this.cursorPosi.start = start;
            this.cursorPosi.end = end;
        },
        getWordNotify: function(usedLen) {
            usedLen = (usedLen ? usedLen : 0);
            var freeLen = this.setting.maxWord - usedLen;
            var notify = this.setting.wordNotify.split('*');
            return notify[0] + '<strong>' + freeLen + '</strong>' + notify[1];
        },
        wordTrace: function() {
            var val = this.textbox.val();
            if (val.length > this.setting.maxWord) {
                this.textbox.val(val.substr(0, this.setting.maxWord));
            }
            $('#wordtracer').html(this.getWordNotify(this.textbox.val().length));
        }
    }
})(jQuery);